package com.yanjr.modules.sys.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yanjr.common.utils.IdGen;
import com.yanjr.common.utils.StringUtils;
import com.yanjr.modules.sys.dao.OfficeDao;
import com.yanjr.modules.sys.dao.UserDao;
import com.yanjr.modules.sys.entity.Office;
import com.yanjr.modules.sys.entity.User;
import com.yanjr.modules.sys.service.OfficeService;
import com.yanjr.modules.sys.utils.UserUtils;

@Service("officeService")
@Transactional(readOnly = true)
public class OfficeServiceImpl implements OfficeService {

	@Autowired
	private OfficeDao officeDao;
	@Autowired
	private UserDao userDao;
	
	@Override
	public Office get(String id) {
		return officeDao.get(id);
	}
	
	@Override
	public Office getOffice(String id) {
		Office office = officeDao.get(id);
		if(office != null) {
			List<User> list = userDao.findByRoleId(id);
			if(list != null && list.size() > 0) {
				office.setUserList(list);
			}
		}
		return office;
	}

	@Override
	public List<Office> findAll() {
		return UserUtils.getOfficeList();
	}

	@Override
	@Transactional(readOnly = false)
	public void save(Office office) {
		User user = UserUtils.getUser();
		
		Office parent = officeDao.get(office.getParentId());
		String oldParentIds = office.getParentIds(); // 获取修改前的parentIds，用于更新子节点的parentIds
		office.setParentIds(parent.getParentIds()+parent.getId()+",");
		
		if(StringUtils.isEmpty(office.getId())) {
			office.setId(IdGen.uuid());
			office.setCreateBy(user.getId());
			office.setCreateDate(new Date());
			office.setUpdateBy(user.getId());
			office.setUpdateDate(new Date());
			
			officeDao.save(office);
		} else {
			office.setUpdateBy(user.getId());
			office.setUpdateDate(new Date());
			
			officeDao.update(office);
		}
		
		// 更新子节点 parentIds
		List<Office> list = officeDao.findByParentIdsLike("%,"+office.getId()+",%");
		for (Office e : list){
			e.setParentIds(e.getParentIds().replace(oldParentIds, office.getParentIds()));
		}
		officeDao.update(list);
		
		UserUtils.removeCache(UserUtils.CACHE_OFFICE_LIST);
	}

	@Override
	@Transactional(readOnly = false)
	public void delete(String id) {
		officeDao.delete(id);
	}

	@Override
	public List<Office> findList(Office office) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Office> findList(Boolean isAll) {
		// TODO Auto-generated method stub
		return null;
	}

}
